use anyhow::Result;
use colored::*;
use std::fs;

pub async fn run(input: String, output: Option<String>, file_type: String) -> Result<()> {
    println!("{} {}", "🗜️  Minifying".cyan(), input);

    let content = fs::read_to_string(&input)?;

    let minified = match file_type.as_str() {
        "css" => basic_css_minify(&content),
        "js" => basic_js_minify(&content),
        _ => return Err(anyhow::anyhow!("Unsupported file type: {}", file_type)),
    };

    if let Some(output_path) = output {
        fs::write(&output_path, &minified)?;
        println!("{} {} → {}", "✅ Saved to".green(), input, output_path);
    } else {
        println!("{}", minified);
    }

    let original_size = content.len();
    let minified_size = minified.len();
    let saved = original_size - minified_size;
    let percentage = if original_size > 0 {
        (saved as f64 / original_size as f64) * 100.0
    } else {
        0.0
    };

    println!(
        "{} {} bytes → {} bytes (saved {:.1}%)",
        "📊 Size:".blue(),
        original_size,
        minified_size,
        percentage
    );

    Ok(())
}

// 简单的 CSS 压缩实现
fn basic_css_minify(content: &str) -> String {
    use regex::Regex;

    let mut result = content.to_string();

    // 移除 CSS 注释
    let css_comments = Regex::new(r"/\*[\s\S]*?\*/").unwrap();
    result = css_comments.replace_all(&result, "").to_string();

    // 移除多余空白和换行
    let multiple_spaces = Regex::new(r"\s+").unwrap();
    result = multiple_spaces.replace_all(&result, " ").to_string();

    // 移除分号、大括号等周围的空格
    let space_around_punct = Regex::new(r"\s*([{}:;,>+~])\s*").unwrap();
    result = space_around_punct.replace_all(&result, "$1").to_string();

    result.trim().to_string()
}

// 简单的 JS 压缩实现（移除多余空白和单行注释）
fn basic_js_minify(content: &str) -> String {
    use regex::Regex;

    let mut result = content.to_string();

    // 移除单行注释
    let single_line_comment = Regex::new(r"//.*$").unwrap();
    result = single_line_comment.replace_all(&result, "").to_string();

    // 移除多行注释
    let multi_line_comment = Regex::new(r"/\*[\s\S]*?\*/").unwrap();
    result = multi_line_comment.replace_all(&result, "").to_string();

    // 移除多余空白（但保持基本结构）
    let multiple_spaces = Regex::new(r"\s+").unwrap();
    result = multiple_spaces.replace_all(&result, " ").to_string();

    // 移除行首和行尾空白
    result.trim().to_string()
}
